package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import model.Comment;
import model.UserInfo;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;
import util.SessionUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

@WebServlet("/addcomment")
public class AddCommentServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String msg = "未知错误";
        int data = 0;
        UserInfo userInfo = SessionUtils.getLoginUser(req);
        if(userInfo != null){
            String text = req.getParameter("text");
            String aidStr = req.getParameter("aid");
            if(!StrUtil.isBlank(text)){
                Connection connection = DBUtils.getConnection();
                String sql = "insert into comment(`text`,uid,aid) values(?,?,?)";
                PreparedStatement statement = connection.prepareStatement(sql);
                statement.setString(1,text);
                statement.setInt(2,userInfo.getUid());
                statement.setInt(3,Integer.valueOf(aidStr));
                data = statement.executeUpdate();
                msg = "";
                DBUtils.close(null,statement,connection);
            }
            else {
                msg = "参数错误！";
            }
        }
        else {
            msg = "未登录！";
        }

        resp.setContentType(AppVar.RESPONSE_CONTENTTYPE_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200,data,msg)));
    }
}
